package com.g17.virtualpetbackend.controller;

import com.g17.virtualpetbackend.entity.User;
import com.g17.virtualpetbackend.service.UserService;
import com.g17.virtualpetbackend.utilty.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashSet;
import java.util.Optional;

@RestController
public class LoginController {

    private static final HashSet<Long> LOGGED_USER = new HashSet<>();

    @Autowired
    UserService userService;

    @PostMapping("/logon")
    Response logon(@RequestParam("username") String username, @RequestParam("password") String password) {
        Optional<User> user = userService.findUserByUsernameAndPassword(username, password);

        if (user.isPresent()) {
            User foundUser = user.get();
            LOGGED_USER.add(foundUser.getId());
            return new Response(foundUser.getId(), Response.OK);
        }

        return new Response(Response.ERROR_ID, Response.ERROR);
    }

    @PostMapping("/logoff")
    Response logoff(@RequestParam("id") Long id) {
        if (LOGGED_USER.contains(id)) {
            LOGGED_USER.remove(id);
            return new Response(id, Response.OK);
        }
        return new Response(Response.ERROR_ID, Response.ERROR);
    }

    @PostMapping("/isLoggedOn")
    Response isLoggedOn(@RequestParam("id") Long id) {
        if (LOGGED_USER.contains(id)){
            return new Response(id, Response.OK);
        }
        return new Response(Response.ERROR_ID, Response.ERROR);
    }
}
